package com.zhongmai.yzfgrabanorder.fragment;

import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhongmai.yzfgrabanorder.R;
import com.zhongmai.yzfgrabanorder.activity.MainActivity;
import com.zhongmai.yzfgrabanorder.base.BaseFragment;
import com.zhongmai.yzfgrabanorder.base.MyApplication;
import com.zhongmai.yzfgrabanorder.bean.AppealOrderItemBean;
import com.zhongmai.yzfgrabanorder.netty_lib.netty.NettyClient;
import com.zhongmai.yzfgrabanorder.utils.Constants;
import com.zhongmai.yzfgrabanorder.utils.EncryptUtils;
import com.zhongmai.yzfgrabanorder.utils.HttpXUtils;
import com.zhongmai.yzfgrabanorder.utils.PlayUtils;
import com.zhongmai.yzfgrabanorder.view.LinkDialog;
import com.zhongmai.yzfgrabanorder.view.LoadingDialog;


import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.zhongmai.yzfgrabanorder.netty_lib.netty.NettyClient.isConnect;
import static com.zhongmai.yzfgrabanorder.utils.Constants.refreshTime;
import static com.zhongmai.yzfgrabanorder.utils.Constants.user;


/**
 * 首页
 */
public class GrabAnOrderFragment extends BaseFragment {
    private Unbinder unbinder;
    @BindView(R.id.mBT_grab_an_order)
    Button mBT_grab_an_order;

    private boolean isBind = false;
    LoadingDialog onlineDialog;

    Handler dlgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    onlineDialog.dismiss();
                    showToast("接单上线");
                    mBT_grab_an_order.setText("停止接单");
                    mBT_grab_an_order.setBackground(getResources().getDrawable(R.mipmap.buttom_stop));
                    break;
                case 1:
                    onlineDialog.dismiss();
                    showToast("接单下线");
                    mBT_grab_an_order.setText("开始接单");
                    mBT_grab_an_order.setBackground(getResources().getDrawable(R.mipmap.buttom_start));
                    break;
                case 2:
                    Constants.manual_link = false;
                    onlineDialog.dismiss();
                    showToast("上线失败");
                    mBT_grab_an_order.setText("开始接单");
                    mBT_grab_an_order.setBackground(getResources().getDrawable(R.mipmap.buttom_start));
                    break;
                default:

                    break;
            }
        }
    };

    public Handler getHandler() {
        return dlgHandler;
    }

    public GrabAnOrderFragment() {
    }

    @Override
    protected int createSuccessView() {
        return R.layout.fragment_grab_an_order;
    }

    @Override
    protected void changeLayout() {
        FragmentsManager.getInstance().addActivity(this);
    }


    @Override
    protected void loadingData() {
        logMag("GrabAnOrderFragment-------loadingData");
        //配置URL
        if (TextUtils.isEmpty(Constants.Url)) {
            LinkDialog linkDialog = new LinkDialog(getContext(), false, new LinkDialog.URLSuccess() {
                @Override
                public void success() {
                    showToast("url配置成功");
                    logMag("url配置成功");
                }
            });
            linkDialog.show();
        }
        judOrder();//查下订单
    }

    @Override
    protected void againLoad() {

    }

    @Override
    protected void switchFragemnt() {
        if (mTV_title != null && mTV_title.getVisibility() == View.VISIBLE) {
            mTV_title.setText("首页");
        }
        if (mBT_grab_an_order != null && mTV_title.getVisibility() == View.VISIBLE) {
            if (NettyClient.isConnect) {
                mBT_grab_an_order.setText("停止接单");
            } else {
                mBT_grab_an_order.setText("开始接单");
            }
        }
    }

    private void judOrder() {
        if (Constants.refresh) {
            RequestParams params = new RequestParams(Constants.Url + Constants.appealALL);
            try {
                params.addHeader("Authorization", user);
                JSONObject json = new JSONObject();

                json.put("pageSize", Constants.page_size);
                json.put("page", 1);
                logMag("是否有订单");
                String def = EncryptUtils.encrypt(json.toString(), Constants.encrypt_key, Constants.encrypt_iv);
                String mdf = EncryptUtils.md5(def + Constants.encrypt_key).toUpperCase();
                params.addBodyParameter("def", def);
                params.addParameter("mdf", mdf);
            } catch (JSONException e1) {
                e1.printStackTrace();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            HttpXUtils.xUtilsPostRequest(getActivity(), params, new HttpXUtils.MyCallback() {
                @Override
                public void myResult(String result) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        if (code.equals("100000")) {
                            String jsonData = jsonObject.getString("data");
                            logMag("data22222------" + jsonData);
                            if (!"[]".equals(jsonData) && !"{}".equals(jsonData)) {
                                MainActivity activity = (MainActivity) getActivity();
                                activity.slidingTabLayoutRedDotShow();
                                PlayUtils.play(R.raw.sms_order);
                                Constants.refresh = false;
                            } else {
                            }
                        } else {
                            String message = jsonObject.getString("message");
                            showToast(message);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(String err) {
                }
            }, false);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @OnClick({R.id.mBT_grab_an_order})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mBT_grab_an_order:
                //                requestOrder();
                changeState();
                break;
            default:
                break;
        }
    }


    /**
     * 改变在线状态
     */
    private void changeState() {
        onlineDialog = new LoadingDialog(getContext());
        if (NettyClient.isConnect) {
            //下线逻辑
            Constants.manual_link = false;
            Constants.refresh = false;
            onlineDialog.show();
            breakLongLink();
            if (Constants.waitOrder) {
                Constants.waitOrder = false;
            }
        } else {
            Constants.manual_link = true;
            Constants.refresh = true;
            onlineDialog.show();
            loadingLink();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (Constants.refresh && !Constants.waitOrder) {
                            Thread.sleep(refreshTime);
                            if (isConnect) {
                                judOrder();
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }


}
